package se.cbb.alfhelper;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.lang3.text.WordUtils;

import se.cbb.lib.ALFScripts;
import se.cbb.lib.AbiskoClusterScripting;
import se.cbb.lib.AbiskoCoreClusterScripting;
import se.cbb.lib.Parameters;
import se.cbb.lib.UppmaxClusterScripting;
import se.cbb.lib.UppmaxCoreClusterScripting;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterDescription;

public class ALFStarter {

	public static void main(String[] args) {
		try {
			Parameters params = new Parameters();
			JCommander vmcmc = new JCommander(params, args);

			if (params.help || params.files.size() < 1) {
				StringBuilder sb = new StringBuilder(65536);
				sb.append("Usage: \n\tjava -jar vmcmc [options] ").append('\n');

				ParameterDescription mainParam = vmcmc.getMainParameter();
				if (mainParam != null) {
					sb.append("Required arguments\n");
					sb.append("     ").append(mainParam.getDescription()).append('\n');
				}
				List<ParameterDescription> params1 = vmcmc.getParameters();
				Field[] fields = params.getClass().getFields();
				for (Field f : fields) {
					for (ParameterDescription p : params1) {
						if (f.getName().equals(p.getField().getName())) {
							sb.append(p.getNames()).append('\n');
							String def = (p.getDefault() == null ? "" : " Default: " + p.getDefault().toString() + '.');
							String desc = WordUtils.wrap(p.getDescription() + def, 120);
							desc = "     " + desc;
							desc = desc.replaceAll("\n", "\n     ") + '\n';
							sb.append(desc);
							break;
						}
					}
				}
				System.out.println(sb.toString());
				return;
			} 
			
			String path = params.files.get(0);
			if(!path.endsWith("/"))
				path = path + "/";
			
//			ALFScripts script = new ALFScripts(path);
//			script.readTrees();
			
			UppmaxCoreClusterScripting.generateScript(path, params.uppmaxProjectName, params.uppmaxProjectTime, params.uppmaxJobName, params.uppmaxScriptName, params.uppmaxFolderIdentifier, params.uppmaxMaxMemory, params.uppmaxMinMemory); 
			UppmaxCoreClusterScripting.generateInformedScript(path, params.uppmaxProjectName, params.uppmaxProjectTime, params.uppmaxJobName, params.uppmaxScriptName + "Informed", params.uppmaxFolderIdentifier, params.uppmaxMaxMemory, params.uppmaxMinMemory, params.duplicationRate, params.lossRate);
			UppmaxCoreClusterScripting.generateRunScript(path);
			UppmaxCoreClusterScripting.generateRunInformedScript(path);
		} catch (Exception e) {
			System.out.println("Error : " + e.getMessage());
			System.exit(-1);
		}
	}


}
